package com.booksystem.campuslibrarymanagementsystem.controller.user;


import com.booksystem.campuslibrarymanagementsystem.commen.request.userquest.Accountrequst.Account;
import com.booksystem.campuslibrarymanagementsystem.commen.request.userquest.Accountrequst.Accountemail;
import com.booksystem.campuslibrarymanagementsystem.commen.request.userquest.Accountrequst.Accountlist;
import com.booksystem.campuslibrarymanagementsystem.commen.result.Result;
import com.booksystem.campuslibrarymanagementsystem.entity.AccountTable;
import com.booksystem.campuslibrarymanagementsystem.service.AccountTableService;
import com.booksystem.campuslibrarymanagementsystem.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RequestMapping("/User")
@Api(tags = "账户信息")
@RestController
public class AccountMessageController {

    @Autowired
    AccountTableService accountTableService;

    EmailSender emailSender; // 注入EmailSender实例

    /*
     账户信息查看功能
       1，通过账户id(学号）查看自己的账户信息
       2，判断账户id(学号）是否为空，或空格，
       3，判断是否该账户id(学号)错误或者不存在
     */
    @PostMapping("/AccountMessage")
    @ApiOperation(value = "账户信息查看", notes = "通过账户id(学号）查看自己的账户信息")
    public Result AccountMessage(@RequestBody Accountlist accountlist) {
        Map<String, Object> parsed = JwtUtil.tokenPre(accountlist.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            Object account = parsed.get("account");
            if (identity.equals("user")) {
                AccountTable information = accountTableService.queryByAccount( (String) account);
                if ((information == null)) {
                    return Result.fail("该账户id(学号)错误或者不存在，请重新输入？");
                } else {
                    return Result.success(information, 1);
                }
            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
    }

    /*
      账户信息修改功能
         1，通过账户id(学号)，找到该账户的账户信息
         2，输入第一次密码，第二次密码，判断两次密码是否一致

         3，更新成功
     */
    @PostMapping("/ChangeAccountMessage")
    @ApiOperation(value = "修改账户密码", notes = "通过账户id(学号）修改自己的账户密码")
    public Result ChangeAccountMessage(@RequestBody Account accounts) {
        Map<String, Object> parsed = JwtUtil.tokenPre(accounts.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            Object account = parsed.get("account");
            if (identity.equals("user")) {
                String password = accounts.getPassword();//第一次密码
                String confirmPassword = accounts.getConfirmPassword(); // 第二次密码

                if ((password == null || password.trim().isEmpty())) {
                    return Result.fail("请输入第一次密码?");
                }else if ((confirmPassword == null || confirmPassword.trim().isEmpty())){
                    return Result.fail("请输入第二次密码?");
                }

                if (!password.equals(confirmPassword)) {
                    // 判断两次输入的密码是否一致
                    return Result.fail("两次输入的密码不一致，请重新输入。");
                }
                    // 查询账户信息
                    AccountTable information = accountTableService.queryByAccount((String) account);
                    if (information != null) {

                        String salt = SaltUtil.saltGet();
                        String psw = password + salt;
                        String generatedHash = HashUtil.HashGet(psw);
                        boolean a = accountTableService.upDataPswAndSalt((String) account, generatedHash, salt);
                        if (a) {
                            String newEmail = information.getEmail();
                            String mage = "您的密码已重置成功";
                            EmailSender.sendEmails(newEmail, mage); // 使用EmailSender发送邮件
                            return Result.success("密码重置成功", 1);
                        } else {
                            return Result.fail("密码重置失败，请联系管理员");
                        }
                    } else {
                        // 没有找到账户信息
                        return Result.fail("账户未找到");
                    }
            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
    }

    // 3，修改邮箱(向原来邮箱发送已经修改为新邮箱为xxxx)，原来邮箱与新邮箱相同，则重新输入,判断邮箱格式
    @PostMapping("/ChangeAccountemail")
    @ApiOperation(value = "修改账户邮箱", notes = "通过账户id(学号）修改自己的账户邮箱")
    public Result ChangeAccountemail(@RequestBody Accountemail accountemail) {
        Map<String, Object> parsed = JwtUtil.tokenPre(accountemail.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            Object account = parsed.get("account");
            if (identity.equals("user")) {
                        String newEmail = accountemail.getEmail();//邮箱
                        String oldEmail = "";
                        if ((newEmail == null || newEmail.trim().isEmpty())) {
                            return Result.fail("邮箱不能为空，请输入要修改的邮箱?");
                        }
                    // 查询账户信息
                    AccountTable information = accountTableService.queryByAccount((String) account);
                    if (information != null) {
                        oldEmail = information.getEmail(); // 保存旧邮箱

                        if (newEmail.matches("^[1-9]\\d{0,9}@qq\\.com$")) {
                            // 判断两次输入的邮箱是否一致
                            if (newEmail.equals(oldEmail)) {
                                return Result.fail("修改的邮箱一致，请重新输入？");
                            }
                            // 更新账户信息
                            information.setEmail(newEmail);
                            boolean updateSuccess = accountTableService.updateAccountemail(information);

                            if (updateSuccess) {
                                // 发送邮件通知到旧邮箱
                                String mage = "尊敬的用户，您的邮箱已从： " + oldEmail + " 更改为： " + newEmail + "。";
                                EmailSender.sendEmails(newEmail, mage); // 使用EmailSender发送邮件
                                System.out.println(mage);
                                return Result.success(information, 1);
                            } else {
                                // 更新失败
                                return Result.fail("更新失败");
                            }
                        } else {
                            return Result.fail("输入的邮箱格式不正确，请重新输入。");
                        }

                    } else {
                        // 没有找到账户信息
                        return Result.fail("账户未找到");
                    }

            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
    }
}
